<?php
/**
 *
 *
 */
class Yz_Form_Element_OneToMany
    extends Yz_Form_Element_MetaElement
{


    /****************************
     *      Public methods      *
     ****************************/


    /**
     *
     *
     */
    public function render(Yz_Template_Interface $template)
    {
        // in fact, just return none if no value
        assert('$this->value instanceof Yz_List');

        // identify 'value type' which appears in links {add|edit|delete}-$type
        $itemClass = $this->value->valueType();
        $itemType = $itemClass::_name_();

        if ('Default' === $itemType)
            $itemType = "";
        else
            $itemType = '-' . Yz_String::fromCamelCase($itemType);

        $m = $this->form->getModule();
        $o = "";

        // render list
        if (! $this->value->isEmpty()) {
            $itemTpl = $m->selectTemplate('ListItemEdit');
            $list = new Yz_Hash($this->value); // convert Yz_List to Yz_Hash
            $list->apply(function($i, $v) use (&$o, $itemTpl, $template) {
                $itemTpl->item = $v;
                $o .= $itemTpl->render($template);
            });
        }

        // render 'add'
        $itemTpl = $m->selectTemplate('ListItemAdd');
        $itemTpl->itemType = $itemType;
        $itemTpl->toItemId = $this->form->getValues()->id;
        $o .= $itemTpl->render($template);

        $js = <<<js
Yz.jquery(function() {
    Yz.loadClass('Yz.Form.OneToMany', function() {
        var f = new Yz.Form('{$this->form->name}');
        var el = new Yz.Form.OneToMany(f,'{$this->name}');
    });
});
js;
        $template->includeJS($this->_class_(), $js);
        return $o;
    }


}
